<template>
  <div class="wrapper">
    <!-- 顶部 -->
    <div class="top">在线商城系统</div>

    <!-- 主体 -->
    <div class="main">
      <!-- 左侧 -->
      <div class="left">
        <img src="../assets/login.png" style="width: 100%;">
      </div>
      <!-- 右侧 -->
      <div class="right">
        <!-- 标题 -->
        <div class="title">欢迎登录</div>
        <!-- 表单 -->
        <el-form :model="user" :rules="rules" ref="userForm" size="normal">
          <el-form-item prop="userName">
            <el-input prefix-icon="el-icon-user" v-model="user.userName" placeholder="请输入账号"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" v-model="user.password" placeholder="请输入密码" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <div style="display: flex;">
              <el-input v-model="code" placeholder="请输入验证码" @keydown.enter.native="login"></el-input>
              <span @click="refreshCode" style="cursor: pointer;">
                <Identify :identifyCode="identifyCode"></Identify>
              </span>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="login">登&nbsp;&nbsp;&nbsp;&nbsp;录</el-button>
            <el-button type="warning" @click="$router.push('/register')">前往注册</el-button>
          </el-form-item>
          <!-- <el-form-item style="margin: 10px 0; text-align: right">
            <el-button type="text" @click="handlePass">忘记密码</el-button>
          </el-form-item> -->
        </el-form>
      </div>
    </div>

    <!-- 忘记密码 -->
    <el-dialog title="忘记密码" :visible.sync="dialogFormVisible" width="30%">
      <el-form :model="pass" :rules="passRules" ref="passForm" size="normal" label-width="100px">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="pass.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="pass.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="passwordBack">重置密码</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { resetRouter, setRoutes } from "@/router";
import Identify from "@/components/Identify";

export default {
  name: "Login",
  data() {
    return {
      user: {
        userName: '',
        password: ''
      },
      pass: {},
      code: '',
      dialogFormVisible: false,
      // 图片验证码
      identifyCode: '',
      // 验证码规则
      identifyCodes: '23456789ABCDEFGHGKMNPQRSTUVWXY',
      rules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
        ],
      },
      passRules: {
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { ppattern: /^1\d{10}$/, message: '手机号不符合格式', }
        ]
      }
    }
  },
  components: { Identify },
  mounted() {
    this.refreshCode()
    // 重置路由
    resetRouter()
  },
  methods: {
    // 生成随机验证码
    refreshCode() {
      this.identifyCode = ''
      for (let i = 0; i < 4; i++) {
        this.identifyCode += this.identifyCodes[Math.floor(Math.random() * this.identifyCodes.length)]
      }
    },
    // 登录
    login() {
      // 判断验证码是否正确
      if (this.code.toLowerCase() !== this.identifyCode.toLowerCase()) {
        this.$message.error("验证码错误")
        this.refreshCode()
        return;
      }
      // 判断表单校验是否合法
      this.$refs['userForm'].validate(async valid => {
        // 表单校验不合法，则返回
        if (!valid) return;

        // 发送请求
        const res = await this.request.post("/user/login", this.user)
        if (res.code !== 200) {
          return this.$message.error(res.msg)
        }

        // 将用户信息存储到本地存储中
        localStorage.setItem("user", JSON.stringify(res.data))
        localStorage.setItem("menus", JSON.stringify(res.data.menus))

        // 动态设置当前用户的路由
        setRoutes()
        // 根据角色跳转到不同的页面
        if (res.data.role === 'ROLE_USER') {
          this.$router.push("/front/home")
        } else {
          this.$router.push("/")
        }
        this.$message.success("登录成功")
      });
    },
    // 显示忘记密码
    handlePass() {
      this.dialogFormVisible = true
      this.pass = {}
    },
    // 忘记密码
    passwordBack() {
      this.$refs['passForm'].validate((valid) => {
        if (!valid) return;

        this.request.put("/user/reset", this.pass).then(res => {
          if (res.code !== 200) {
            this.$message.error(res.msg)
          }
          this.$message.success("重置密码成功，新密码为：123，请尽快修改密码")
          this.dialogFormVisible = false
        })
      })
    }
  }
}
</script>

<style scoped style="less">
.wrapper {
  height: 100vh;
  background-image: linear-gradient(to bottom right, #4169E1, #87CEFA);
  overflow: hidden;

  /* 顶部 */
  .top {
    height: 60px;
    line-height: 60px;
    font-size: 20px;
    padding-left: 50px;
    color: white;
    background-color: rgba(0, 0, 0, 0.2)
  }

  /* 主体 */
  .main {
    width: 50%;
    margin: 150px auto;
    background-color: white;
    border-radius: 10px;
    display: flex;
    overflow: hidden;

    /* 左侧 */
    .left {
      width: 40%;
    }

    /* 右侧 */
    .right {
      width: 350px;
      margin-top: 30px;
      margin-left: 50px;

      .title {
        margin: 20px 0;
        text-align: center;
        font-size: 24px;
        font-weight: bold;
        letter-spacing: 6px;
      }
    }
  }
}
</style>
